package com.micro.fast.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.http.HttpStatus;
import javax.servlet.http.HttpServletRequest;

/**
 * 对options类型的跨域预请求进行快速处理,未启动
 * @author lsy
 */
public class PreRequestFilter extends ZuulFilter {

    /**
     * 对options类型的跨域预请求进行快速处理
     */
    private static final String OPTIONS = "OPTIONS";

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String method = request.getMethod();
        if (OPTIONS.equals(method)){
            //不进行后续操作，直接过滤请求,返回200状态码
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.OK.value());
        }else{
            //对请求进行后续处理
            requestContext.setSendZuulResponse(true);
        }
        return null;
    }
}
